﻿using Microsoft.Build.Evaluation;
using OD.ProjectCustomizationTool.Helpers;
using OD.ToolBox.IO;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace OD.ProjectCustomizationTool.Tools
{
    internal sealed class AssemblySigner : ProjectUpdaterFromQualityFileBase
    {

        #region Properties

        private static String PathToSnExe { get { return PathHelper.BuildFullPathToResource("sn.exe"); } }
        private const String KeyFileExtension = ".snk";
        private const String AssemblyOriginatorKeyFileItemType = "None";

        private String SolutionName
        {
            get
            {
                var solutionFile = this.SolutionRoot.GetFiles("*.sln").FirstOrDefault();
                if (solutionFile == null)
                    return null;
                else
                    return Path.GetFileNameWithoutExtension(solutionFile.Name);
            }
        }

        protected override string QualityFileName
        {
            get
            {
                return this.SolutionName + AssemblySigner.KeyFileExtension;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Creates a key file in order to apply a strong name to assemblies.
        /// <see cref="http://msdn.microsoft.com/en-us/library/6f05ezxy.aspx"/>
        /// </summary>
        protected override void InternalCreateQualityFile()
        {
            this.Monitor.Logger.WriteLine("Generating strong named file " + this.QualityFileFullPath);
            Process.Start(AssemblySigner.PathToSnExe, "-k \"" + this.QualityFileFullPath + "\"");
        }

        /// <summary>
        /// Signs an assembly with the given strong name. If the key file does not exist, then it will be automatically created.
        /// <remarks>The registration is a link to .Quality common folder.</remarks>
        /// <see cref="http://msdn.microsoft.com/en-us/library/xc31ft41.aspx"/>
        /// </summary>
        protected override void InternalUpdate()
        {
            this.SetProjectProperty(Properties.Resources.SignAssemblyProjectProperty, true.ToString());
            this.SetProjectProperty(Properties.Resources.AssemblyOriginatorKeyFileProjectProperty, this.RelativePathToQualityFile);
        }

        #endregion

    }
}
